﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.Common;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using TRPOP.Config;
using TRPOP.CMS.Model;

namespace TRPOP.CMS.Publish
{
    public class PubTaskDAL
    {
        /// <summary>
        /// 获取第一个可以执行的任务
        /// </summary>
        /// <returns></returns>
        public static PubTaskInfo GetTopMustExecInfo()
        {
            PubTaskInfo oPubTaskInfo = null;
            string strSql = string.Format(" SELECT TOP 1 * FROM  {0}_pub_pubTask  WHERE intTaskStatus = {1} ORDER BY intPubTaskId ASC", SystemInfoHelper.getSystemInfo().DBprefixTableName, (int)PubTaskKeys.TaskStatusType.IsNotStarted);
            DataTable oTable = CommonDAL.GetDatatablebyReader(strSql, SystemInfoHelper.getSystemInfo().CMSDataBaseConnection);
            if (oTable != null && oTable.Rows.Count > 0)
            {
                oPubTaskInfo = ParseRowTomodel(oTable.Rows[0]);
            }
            return oPubTaskInfo;
        }
        /// <summary>
        /// 获取第一个可以执行的任务
        /// </summary>
        /// <param name="intUserID"></param>
        /// <returns></returns>
        public static PubTaskInfo GetTopMustExecInfo(int intUserID)
        {
            PubTaskInfo oPubTaskInfo = null;
            string strSql = string.Format(@" SELECT TOP 1 * 
                                             FROM  {0}_pub_pubTask  
                                             WHERE intTaskStatus = {1} AND intAdminID={2} 
                                             ORDER BY intPubTaskId ASC",
                                         SystemInfoHelper.getSystemInfo().DBprefixTableName, (int)PubTaskKeys.TaskStatusType.IsNotStarted, intUserID);
            DataTable oTable = CommonDAL.GetDatatablebyReader(strSql, SystemInfoHelper.getSystemInfo().CMSDataBaseConnection);
            if (oTable != null && oTable.Rows.Count > 0)
            {
                oPubTaskInfo = ParseRowTomodel(oTable.Rows[0]);
            }
            return oPubTaskInfo;
        }
        ///	<summary>
        ///	 更新或添加
        ///	</summary>
        ///	<param name="oInfo"></param>
        ///	<returns>bool</returns>
        public static bool Save(PubTaskInfo oInfo)
        {
            bool flag = false;
            try
            {
                SqlDatabase odbDataBase = new SqlDatabase(SystemInfoHelper.getSystemInfo().CMSDataBaseConnection);
                DbCommand odbCommand = odbDataBase.GetStoredProcCommand(SystemInfoHelper.getSystemInfo().DBprefixTableName + "_" + "pubTask_Save");
                ParseModeltoParam(odbDataBase, odbCommand, oInfo);
                odbDataBase.ExecuteNonQuery(odbCommand);
                oInfo.intPubTaskId = (int)odbDataBase.GetParameterValue(odbCommand, "@intPubTaskId");
                flag = true;
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
            return flag;
        }

        /// <summary>
        /// 根据用户id获取已经执行过的发布任务
        /// </summary>
        /// <param name="intUserID"></param>
        /// <returns></returns>
        public static DataTable GetExecedInfo(int intUserID)
        {
            string strStatus = ((int)PubTaskKeys.TaskStatusType.IsExecuteSuccess).ToString();
            strStatus += "," + (int)PubTaskKeys.TaskStatusType.IsExecuteError;
            strStatus += "," + (int)PubTaskKeys.TaskStatusType.IsProgrameError;
            string strSql = string.Format(@" SELECT intPubTaskId , intTaskStatus 
                                             FROM   {0}_pub_pubTask  
                                             WHERE  intTaskStatus in ({1}) AND intAdminID={2}
                                             ORDER  BY intPubTaskId ASC",
                                          SystemInfoHelper.getSystemInfo().DBprefixTableName, strStatus, intUserID);
            return CommonDAL.GetDatatablebyReader(strSql, SystemInfoHelper.getSystemInfo().CMSDataBaseConnection);
        }
        /// <summary>
        /// 删除用户的所有任务
        /// </summary>
        /// <param name="intUserID"></param>
        /// <returns></returns>
        public static bool DeleteAllInfoUserId(int intUserID)
        {
            string strSqlString = "DELETE  FROM " + SystemInfoHelper.getSystemInfo().DBprefixTableName + "_pub_pubTask WHERE   intAdminID=" + intUserID + "    ";
            try
            {
                return CommonDAL.ExeSQLQuery(strSqlString, SystemInfoHelper.getSystemInfo().CMSDataBaseConnection) == Common.EnumSubmitResult.Success;
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
        }
        /// <summary>
        /// 取消用户的所有任务
        /// </summary>
        /// <param name="intUserID"></param>
        /// <returns></returns>
        public static bool CancelAllInfoUserId(int intUserID)
        {
            string strSqlString = "UPDATE   " + SystemInfoHelper.getSystemInfo().DBprefixTableName + "_pub_pubTask  SET intTaskStatus = {0} WHERE   intAdminID={1} ";
            strSqlString = string.Format(strSqlString, (int)PubTaskKeys.TaskStatusType.IsCanceled, intUserID);
            try
            {
                return CommonDAL.ExeSQLQuery(strSqlString, SystemInfoHelper.getSystemInfo().CMSDataBaseConnection) == Common.EnumSubmitResult.Success;
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
        }
        /// <summary>
        /// 信息操作结果已显示给用户
        /// </summary>
        /// <param name="intPubTaskId"></param>
        /// <returns></returns>
        public static bool ShowedInfoById(int intPubTaskId)
        {
            string strSqlString = "UPDATE " + SystemInfoHelper.getSystemInfo().DBprefixTableName + "_pub_pubTask SET intTaskStatus={0} WHERE intPubTaskId=" + intPubTaskId + "    ";
            strSqlString = string.Format(strSqlString, (int)PubTaskKeys.TaskStatusType.IsShowed);
            try
            {
                return CommonDAL.ExeSQLQuery(strSqlString, SystemInfoHelper.getSystemInfo().CMSDataBaseConnection) == Common.EnumSubmitResult.Success;
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
        }
        ///	<summary>
        ///	 根据Primary Key删除信息实体
        ///	</summary>
        ///	<param name="intPubTaskId"></param>
        ///	<returns>bool</returns>
        public static bool DeleteInfoById(int intPubTaskId)
        {
            string strSqlString = "DELETE  FROM " + SystemInfoHelper.getSystemInfo().DBprefixTableName + "_pub_pubTask WHERE   intPubTaskId=" + intPubTaskId + "    ";
            try
            {
                return CommonDAL.ExeSQLQuery(strSqlString, SystemInfoHelper.getSystemInfo().CMSDataBaseConnection) == Common.EnumSubmitResult.Success;
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
        }
        ///	<summary>
        ///	 根据Primary Key删除信息实体
        ///	</summary>
        ///	<param name="intintPubTaskId"></param>
        ///	<returns>bool</returns>
        public static bool DeletePastTask()
        {
            string strSqlString = "DELETE FROM {0}_pub_pubTask WHERE [intTaskStatus] <> 1 AND dtAddTime <= DATEADD(MONTH,-3,GETDATE())  ";
            strSqlString = string.Format(strSqlString, SystemInfoHelper.getSystemInfo().DBprefixTableName);
            try
            {
                return CommonDAL.ExeSQLQuery(strSqlString, SystemInfoHelper.getSystemInfo().CMSDataBaseConnection) == Common.EnumSubmitResult.Success;
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
        }
        ///	<summary>
        ///	根据Primary Key获取信息实体
        ///	</summary>
        ///	<param name="intintPubTaskId"></param>
        ///	<returns>pubTaskInfo</returns>
        public static PubTaskInfo GetInfoById(int intintPubTaskId)
        {
            PubTaskInfo oInfo = null;
            string strSqlString = "SELECT * FROM " + SystemInfoHelper.getSystemInfo().DBprefixTableName + "_pub_pubTask WHERE  intPubTaskId=" + intintPubTaskId + "    ";
            try
            {
                DataTable oDataTable = CommonDAL.GetDatatablebyReader(strSqlString, SystemInfoHelper.getSystemInfo().CMSDataBaseConnection);
                if (oDataTable != null && oDataTable.Rows.Count == 1)
                {
                    oInfo = ParseRowTomodel(oDataTable.Rows[0]);
                }
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
            return oInfo;
        }

        #region 私有的方法 和属性
        private static TRPOP.ComSqlDAL.ICommonDAL CommonDAL = TRPOP.CMS.Plugin.ICommonDALAccess.GetInstance();
        ///	<summary>
        ///	从Table取数据到实体
        ///	</summary>
        ///	<param name="oDataRow">数据行</param>
        ///	<returns>返回实体</returns>
        private static PubTaskInfo ParseRowTomodel(DataRow oDataRow)
        {
            PubTaskInfo oInfo = new PubTaskInfo();
            oInfo.dtAddTime = oDataRow["dtAddTime"] is DBNull ? (new DateTime(1900, 1, 1)) : (DateTime)oDataRow["dtAddTime"];
            oInfo.intTaskStatus = oDataRow["intTaskStatus"] is DBNull ? 0 : (int)oDataRow["intTaskStatus"];
            oInfo.intAdminID = oDataRow["intAdminID"] is DBNull ? 0 : (int)oDataRow["intAdminID"];
            oInfo.nvcActiontype = oDataRow["nvcActiontype"] is DBNull ? "" : (string)oDataRow["nvcActiontype"];
            oInfo.intNodeID = oDataRow["intNodeID"] is DBNull ? 0 : (int)oDataRow["intNodeID"];
            oInfo.nvcNodeName = oDataRow["nvcNodeName"] is DBNull ? "" : (string)oDataRow["nvcNodeName"];
            oInfo.nvcContentIDs = oDataRow["nvcContentIDs"] is DBNull ? "" : (string)oDataRow["nvcContentIDs"];
            oInfo.intIndexPage = oDataRow["intIndexPage"] is DBNull ? 0 : (int)oDataRow["intIndexPage"];
            oInfo.intCountNum = oDataRow["intCountNum"] is DBNull ? 0 : (int)oDataRow["intCountNum"];
            oInfo.intPubTaskId = oDataRow["intPubTaskId"] is DBNull ? 0 : (int)oDataRow["intPubTaskId"];
            return oInfo;
        }

        ///	<summary>
        ///	通用的添加存储过程的变量
        ///	</summary>
        ///	<param name="osdDataBase">SqlDatabase</param>
        ///	<param name="odbCommand">DbCommand</param>
        ///	<param name="oInfo">实体</param>
        private static PubTaskInfo ParseModeltoParam(SqlDatabase odbDataBase, DbCommand odbCommand, PubTaskInfo oInfo)
        {
            odbDataBase.AddInParameter(odbCommand, "@dtAddTime", System.Data.DbType.DateTime, oInfo.dtAddTime);
            odbDataBase.AddInParameter(odbCommand, "@intTaskStatus", System.Data.DbType.Int32, oInfo.intTaskStatus);
            odbDataBase.AddInParameter(odbCommand, "@intAdminID", System.Data.DbType.Int32, oInfo.intAdminID);
            odbDataBase.AddInParameter(odbCommand, "@nvcActiontype", System.Data.DbType.String, oInfo.nvcActiontype);
            odbDataBase.AddInParameter(odbCommand, "@intNodeID", System.Data.DbType.Int32, oInfo.intNodeID);
            odbDataBase.AddInParameter(odbCommand, "@nvcNodeName", System.Data.DbType.String, oInfo.nvcNodeName);
            odbDataBase.AddInParameter(odbCommand, "@nvcContentIDs", System.Data.DbType.String, oInfo.nvcContentIDs);
            odbDataBase.AddInParameter(odbCommand, "@intIndexPage", System.Data.DbType.Int32, oInfo.intIndexPage);
            odbDataBase.AddInParameter(odbCommand, "@intCountNum", System.Data.DbType.Int32, oInfo.intCountNum);
            odbDataBase.AddParameter(odbCommand, "@intPubTaskId", System.Data.DbType.Int32, ParameterDirection.InputOutput, null, DataRowVersion.Default, oInfo.intPubTaskId);
            return oInfo;
        }

        #endregion

    }
}
